package edu.spec.basic.controller;

import edu.spec.basic.model.Module;
import edu.spec.basic.model.dto.ExtGridReturn;
import edu.spec.basic.model.dto.MvcReturn;
import edu.spec.basic.model.enumeration.Status;
import edu.spec.basic.service.iface.ICommandService;
import edu.spec.basic.service.iface.IModuleService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.inject.Inject;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin/module")
public class ModuleController {

    @Inject
    private IModuleService moduleService;
	@Inject
	private ICommandService commandService;

    @ResponseBody
    @RequestMapping("/allModuleAndCommand")
    public Object listAllModuleAndCommand(){
	    Map<String, Object> mcMap = new HashMap<String, Object>();
	    mcMap.put("allModule", moduleService.listAllModule());
		mcMap.put("allCommand", commandService.listAllCommand());
        return new MvcReturn(true, mcMap);
    }

	@ResponseBody
	@RequestMapping("/allModule")
	public Object listAllModule(){
		return new MvcReturn(true, moduleService.listAllModule());
	}

	@ResponseBody
	@RequestMapping("/listModuleByParent")
	public Object listModuleByParent(@RequestParam int id){
//		SystemContext.setOrder("orderNum");
		List<Module> childModule = moduleService.listModuleByParent(id);
		return new ExtGridReturn((long)childModule.size(), childModule);
	}

	@ResponseBody
	@RequestMapping("/add")
	public Object addModule(Module module, @RequestParam int parentId){
		Module parent = moduleService.load(parentId);
		module.setParent(parent);
		moduleService.add(module);
		return new MvcReturn(true);
	}

	@ResponseBody
	@RequestMapping("/delete/{id}")
	public Object delete(@PathVariable int id){
		moduleService.delete(id);
		return new MvcReturn(true);
	}

	@ResponseBody
	@RequestMapping("/update")
	public Object update(Module m){
		Module dbm = moduleService.load(m.getId());
		dbm.setOrderNum(m.getOrderNum());
		dbm.setIconClz(m.getIconClz());
		dbm.setChinese(m.getChinese());
		dbm.setStatus(m.getStatus());
		dbm.setEnglish(m.getEnglish());
		dbm.setUpdateTime(new Date());
		dbm.setUrl(m.getUrl());
		moduleService.update(dbm);
		return new MvcReturn(true);
	}

	@ResponseBody
	@RequestMapping("/toggleStatus/{id}")
	public Object toggleStatus(@PathVariable int id){
		Module m = moduleService.load(id);
		if(m.getStatus()== Status.DISABLED){
			m.setStatus(Status.ENABLED);
		}else{
			m.setStatus(Status.DISABLED);
		}
		moduleService.update(m);
		return new MvcReturn(true);
	}

}
